﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;

namespace HybridLab.Workflow.Activities.UI
{
	internal class PropertyErrorManager : IDataErrorInfo
	{
		private EventHandler ErrorChangedHandler;
		private Dictionary<string, string> properties = new Dictionary<string, string>();

		internal event EventHandler ErrorChanged
		{
			add
			{
				EventHandler handler2;
				EventHandler errorChanged = ErrorChangedHandler;
				do
				{
					handler2 = errorChanged;
					EventHandler handler3 = (EventHandler)Delegate.Combine(handler2, value);
					errorChanged = Interlocked.CompareExchange<EventHandler>(ref ErrorChangedHandler, handler3, handler2);
				}
				while (errorChanged != handler2);
			}
			remove
			{
				EventHandler handler2;
				EventHandler errorChanged = ErrorChangedHandler;
				do
				{
					handler2 = errorChanged;
					EventHandler handler3 = (EventHandler)Delegate.Remove(handler2, value);
					errorChanged = Interlocked.CompareExchange<EventHandler>(ref ErrorChangedHandler, handler3, handler2);
				}
				while (errorChanged != handler2);
			}
		}

		protected PropertyErrorManager()
		{
		}

		protected void ClearPropertyError(string propertyName)
		{
			int count = properties.Count;
			properties.Remove(propertyName);
			if (count != this.properties.Count)
			{
				RaiseEvent(ErrorChangedHandler);
			}
		}

		protected void RaiseEvent(EventHandler eventToRaise)
		{
			if (eventToRaise != null)
			{
				eventToRaise(this, null);
			}
		}

		protected void SetPropertyError(string propertyName, string errorMessage)
		{
			properties[propertyName] = errorMessage;
			RaiseEvent(ErrorChangedHandler);
		}

		public string Error
		{
			get
			{
				if ((properties == null) || (properties.Count <= 0))
				{
					return null;
				}
				StringBuilder builder = new StringBuilder();
				foreach (string key in properties.Keys.OrderBy(k => k))
				{
					builder.AppendLine(string.Format("{0}:{1}", key, properties[key]));
				}
				return builder.ToString();
			}
		}

		public string this[string columnName]
		{
			get
			{
				string val = null;
				if (properties != null)
				{
					properties.TryGetValue(columnName, out val);
				}
				if (val == null)
				{
					return string.Empty;
				}
				return val;
			}
		}

		internal int TotalInvalidProperties
		{
			get
			{
				if (properties == null)
				{
					return 0;
				}
				return properties.Count;
			}
		}
	}
}